package de.koller.aframe.plain;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.image.VolatileImage;

public class FastSprite {
	
	private final Sprite sprite;
	private VolatileImage fastSprite;
	private GraphicsConfiguration graphicsConfiguration = null;
	
	public FastSprite( Sprite sprite ) {
		this.sprite = sprite;
	}
	
	private GraphicsConfiguration getGrConf() {
		if( graphicsConfiguration != null )
			return graphicsConfiguration;
		
		GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
		graphicsConfiguration = ge.getDefaultScreenDevice().getDefaultConfiguration();
		return graphicsConfiguration;
	}
	
	private void createVolatile() {
		GraphicsConfiguration gc = getGrConf();
		fastSprite = gc.createCompatibleVolatileImage( sprite.width, sprite.height, Transparency.BITMASK );
		
		int valid = fastSprite.validate( gc );
		if( valid == VolatileImage.IMAGE_INCOMPATIBLE ) {
			this.createVolatile();
			return;
		}
		
		Graphics2D g = null;
		do {
			g = fastSprite.createGraphics();
			
			Composite sc = g.getComposite();
			g.setComposite( AlphaComposite.Src );
			g.setColor( Color.BLACK );
			g.clearRect( 0, 0, fastSprite.getWidth(), fastSprite.getHeight() );
			
			g.setComposite( sc );
			sprite.render( g, 0, 0, sprite.width, sprite.height, 0 );
			g.dispose();
		} while( fastSprite.contentsLost() );
	}
	
	public void render( Graphics2D g, float x, float y, float w, float h, float r ) {
		GraphicsConfiguration gc = getGrConf();
		
		if( fastSprite == null || fastSprite.validate( gc ) != VolatileImage.IMAGE_OK )
			this.createVolatile();
		
		AffineTransform a = sprite.createTransform( x, y, w, h, r );
		g.drawImage( sprite.image, a, null );
	}
	
}
